package net.zoneland.knowledge.utils;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.branchitech.account.ldap.UserBean;
import com.google.common.collect.Lists;
import com.google.gson.reflect.TypeToken;

import net.zoneland.knowledge.cache.RedisCacheUtil;
import net.zoneland.knowledge.constant.BizConstant;
import net.zoneland.knowledge.model.UserRoleRel;
import net.zoneland.knowledge.service.RoleService;
import net.zoneland.uniflow.client.UserInfo;

/**
 * 业务缓存工具类.
 * @author zmq
 * @Date 2021/12/23 17:46
 */
public final class BizCacheUtils {
    /**
     * 日志.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(BizCacheUtils.class);
    /**
     * 私有构造.
     */
    private BizCacheUtils() {

    }

    /**
     * 获取指定角色的缓存人员uid.
     * @param roleService 角色业务接口
     * @param roleId 角色id
     * @param redisCacheUtil 缓存业务接口
     * @return 用户userId集合
     */
    public static Set<String> getUserRoleRels(final RoleService roleService, final String roleId,
                                        final RedisCacheUtil redisCacheUtil) {
        String json = redisCacheUtil.hget(BizConstant.ROLE_USER_CACHE_KEY, roleId);
        if (StringUtils.isNotBlank(json)) {
            return GsonUtils.GSON.fromJson(json, new TypeToken<Set<String>>() { }.getType());
        }
        Set<String> users = roleService.getByRoleIds(Lists.newArrayList(roleId))
            .stream().map(UserRoleRel::getUserid).collect(Collectors.toSet());
        if (CollectionUtils.isNotEmpty(users)) {
            redisCacheUtil.hset(BizConstant.ROLE_USER_CACHE_KEY, roleId,
                GsonUtils.GSON.toJson(users), BizConstant.CUSTOM_MANAGER_PERMISSION_CACHE_EXPIRE_HOURS);
        }
        return users;
    }

    /**
     * 获取角色-公司-人员集合.
     * @param companyDn 公司dn
     * @param roleIds 角色id
     * @param redisKey redis的key
     * @param redisCacheUtil redis缓存工具类
     * @param roleService 角色业务接口
     * @return 角色人员集合
     */
    public static List<UserInfo> getRoleUsers(final String companyDn, final List<String> roleIds,
                                              final String redisKey, final RedisCacheUtil redisCacheUtil,
                                              final RoleService roleService) {
        String json = redisCacheUtil.hget(redisKey, companyDn);
        if (StringUtils.isNotBlank(json)) {
            return GsonUtils.GSON.fromJson(json, new TypeToken<List<UserInfo>>() { }.getType());
        }
        List<UserRoleRel> roleUsers = roleService.getByRoleIds(roleIds);
        List<UserInfo> res = null;
        if (CollectionUtils.isNotEmpty(roleUsers)) {
            Map<String, UserInfo> userIdMap = roleUsers.stream().map(x -> {
                UserBean user = UserBean.getInstanceByID(x.getUserid());
                return user == null ? null : new UserInfo(user.getUserID(), user.getUserName());
            }).filter(Objects::nonNull).collect(Collectors.toMap(UserInfo::getUserId, it -> it));

            //设置缓存
            roleUsers.stream().collect(Collectors.groupingBy(UserRoleRel::getRestraint)).entrySet().stream().forEach(it -> {
                List<UserInfo> userInfos = it.getValue().stream()
                    .map(userIdMap::get).filter(Objects::nonNull).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(userInfos)) {
                    redisCacheUtil.hset(redisKey, companyDn,
                        GsonUtils.GSON.toJson(userInfos), BizConstant.CUSTOM_MANAGER_PERMISSION_CACHE_EXPIRE_HOURS);
                }
            });
            res = roleUsers.stream().filter(it -> StringUtils.equals(companyDn, it.getRestraint()))
                .map(x -> userIdMap.get(x.getUserid())).filter(Objects::nonNull).collect(Collectors.toList());
        }
        return res;
    }

}
